/*
 * @lc app=leetcode.cn id=640 lang=cpp
 *
 * [640] 求解方程
 */

// @lc code=start
#include <bits/stdc++.h>
using namespace std;
class Solution
{
    bool isNum(char c)
    {
        return c >= '0' && c <= '9';
    }
    int toNumber(int &i, const string &s)
    {
        int j = i;
        int tmp = 0;
        while (j < s.size() && isNum(s[j]))
        {
            tmp *= 10;
            tmp += s[j] - '0';
            ++j;
        }
        i = j;
        return tmp;
    }
    vector<int> huajian(string &s)
    {
        vector<int> v(2, 0); // v[0] 表示 常数， x[1] 表示 x 的系数
        for (int i = 0; i < s.size();)
        {
            switch (s[i])
            {
            case '+':
            case '-':
            {
                int sign = 1;
                if(s[i] == '-')
                    sign = -sign;

                i++;
                if (s[i] != 'x')
                {
                    int tmp = toNumber(i, s);
                    if (i < s.size() && s[i] == 'x')
                    {
                        v[1] += sign * tmp;
                        ++i;
                    }
                    else
                    {
                        v[0] += sign * tmp;
                    }
                }
                else
                {
                    v[1] += sign;
                    ++i;
                }
                break;
            }
            case 'x':
                v[1]++;
                ++i;
                break;
            default:
                int tmp = toNumber(i, s);
                if(i < s.size() && s[i] == 'x')
                {
                    ++i;
                    v[1] += tmp;
                }
                else
                {
                    v[0] += tmp;
                }
                break;
            }
        }

        return v;
    }

public:
    string solveEquation(string equation)
    {
        auto pos = equation.find('=');
        auto l = equation.substr(0, pos);
        auto r = equation.substr(pos + 1, equation.size() - pos - 1);

        auto lv = huajian(l);
        auto rv = huajian(r);
        int changshu = lv[0] - rv[0];
        int factor = rv[1] - lv[1];
        if(factor == 0)
        {
            if(changshu == 0)
            {
                return "Infinite solutions";
            }
            else
            {
                return "No solution";
            }
        }
        else
        {
            return "x=" + to_string(changshu / factor);
        }
    }
};
// @lc code=end
